package com.sgx.learning.luban.homework;

import com.sgx.learning.luban.homework.attributes.AttributeInfo;
import com.sgx.learning.luban.homework.basictype.U2;
import com.sgx.learning.luban.homework.basictype.U4;
import com.sgx.learning.luban.homework.constantpool.ConstantClassInfo;
import com.sgx.learning.luban.homework.constantpool.ConstantPoolInfo;
import com.sgx.learning.luban.homework.constantpool.ConstantUtf8Info;
import com.sgx.learning.luban.homework.fieldinfo.FieldInfo;
import com.sgx.learning.luban.homework.methodsinfo.MethodInfo;
import lombok.Data;

import java.nio.file.attribute.BasicFileAttributes;

@Data
public class ClassFile {
    private U4 magic;
    private U2 minorVersion;
    private U2 majorVersion;
    private U2 constantPoolCount;
    private ConstantPoolInfo[] constantPools;
    private U2 accessFlags;
    private U2 thisClass;
    private U2 superClass;
    private U2 interfacesCount;
    private ConstantClassInfo[] interfaces;
    private U2 fieldCount;
    private FieldInfo[] fieldInfos;
    private U2 methodsCount;
    private MethodInfo[] methodsInfo;
    private U2 attributesCount;
    private AttributeInfo[] attributes;

    private BasicFileAttributes basicFileAttributes;
    private String path;

    public void toDisplay(){
        //打印文件信息
        String tab = "\t";
        System.out.println("Class file " + path);
        System.out.println(tab + "Last modified " + basicFileAttributes.lastModifiedTime() + "; size "+ basicFileAttributes.size() + " bytes");
        System.out.println(tab + "Comiled from \"" + path.substring(path.lastIndexOf('\\')).replace(".class",""));
        //打印类编译信息
        ConstantClassInfo thisClassInfo = (ConstantClassInfo) getConstantByIndex(this.thisClass.getValue());
        ConstantUtf8Info thisClassInfoUtf = (ConstantUtf8Info) getConstantByIndex(thisClassInfo.getIndex());
        System.out.println("public " + thisClassInfoUtf.getBytesValue());
        System.out.println(tab + "minor version: " + this.minorVersion.getValue());
        System.out.println(tab + "major version: " + this.majorVersion.getValue());
        System.out.println(tab + "flags: " + AccessFlagFormatUtils.getClassAccess(this.accessFlags.getValue()));
        System.out.println("Constant pool:");
        for (int i = 0; i < constantPools.length; i++) {
            ConstantPoolInfo temp = constantPools[i];
            System.out.println(tab + "#" + (i+1) + " = " + temp.getTagString());
        }
    }

    private ConstantPoolInfo getConstantByIndex(short index) {
        return constantPools[index - 1];
    }
}
